package com.zhu.oj.service.adapter;

import com.zhu.oj.model.vo.AIChatStreamResponse;


import io.github.pigmesh.ai.deepseek.core.chat.ChatCompletionChoice;
import io.github.pigmesh.ai.deepseek.core.chat.ChatCompletionResponse;
import reactor.core.publisher.Flux;

import java.util.List;
import java.util.Objects;
import java.util.function.Function;
import java.util.stream.Collectors;

public class AiAdapter {


    /**
     * 公共的 Function，用于从 choices 列表中提取 content 字符串。
     * 因为 Service 层做缓存和 Adapter 层做数据映射都需要它，所以设为 public static。
     */
    public static final Function<List<ChatCompletionChoice>, String> choicesProcess = choices ->
            choices.stream()
                    .map(choice -> choice.delta().content())
                    .filter(Objects::nonNull)
                    .collect(Collectors.joining(""));

    public static Flux<AIChatStreamResponse> buildAIChatStreamResponse(Flux<ChatCompletionResponse> chatCompletionResponseFlux) {
        return chatCompletionResponseFlux.map(originalResponse -> {
            String content = originalResponse.choices().stream()
                    .map(choice -> choice.delta().content())
                    .filter(Objects::nonNull)
                    .collect(Collectors.joining(""));
            Integer promptTokens = (originalResponse.usage() != null) ? originalResponse.usage().promptTokens() : null;
            Integer completionTokens = (originalResponse.usage() != null) ? originalResponse.usage().completionTokens() : null;

            return new AIChatStreamResponse(content, promptTokens, completionTokens, null);
        });

    }
}
